package com.yanqu.road.server.manager.activity.chuhan.activity;

import com.google.protobuf.AbstractMessage;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eTongBingTaskType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.activity.chuhan.ChuHanConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.TongBingProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityInfoMgr;
import com.yanqu.road.server.manager.activity.chuhan.CrossChuHanConfigMgr;
import com.yanqu.road.server.manager.activity.chuhan.task.BaseCrossChuHanTask;
import com.yanqu.road.server.manager.scene.CrossSceneMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.AgentProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

/**
 * 放一些配置的东西
 */
public class CrossChuHanBaseActivity {

    protected static Logger logger = LogManager.getLogger(CrossChuHanBaseActivity.class.getName());

    // ============================== 锁 ==============================

    /**
     * 大锁
     */
    protected final Object lock = new Object();
    /**
     *
     */
    protected Map<Long, Object> userLockMap = new ConcurrentHashMap<>();

    // ============================== 停线程 ==============================

    private boolean isStop = false;

    public void setStop(boolean stop) {
        isStop = stop;
    }

    // ============================== 定时器 ==============================

    /**
     * 单独线程
     */
    protected Thread thread = new Thread(new DelayQueueRun());

    protected class DelayQueueRun implements Runnable {
        @Override
        public void run() {
            while (true) {

                if (isStop) {
                    return;
                }

                try {
                    BaseCrossChuHanTask task = taskQueue.take();

                    // 活动结束的任务：
                    if (task.getBeginTime() > config.getActivityInfo().getEndTime() * 1000L) {
                        if (task.getType() != eTongBingTaskType.SetWinner
                                && task.getType() != eTongBingTaskType.SendUnionHonor) {
                            continue;
                        }
                    }

                    // 正常执行
                    try {
                        task.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 定时器执行队列
     */
    protected DelayQueue<BaseCrossChuHanTask> taskQueue = new DelayQueue<>();

    /**
     * 添加task，随便加，使用时会再校验时间
     */
    public void addTask(BaseCrossChuHanTask task) {
        taskQueue.add(task);
    }

    // ============================== 配置 ==============================

    /**
     * 活动配置
     */
    protected ChuHanConfig config;

    /**
     * 榜单长度
     */
    protected int userMaxRank;
    protected int unionMaxRank;
    protected int campMaxRank;

    private List<Long> unionZhanGongLevelParams = new ArrayList<>();

    protected CrossChuHanBaseActivity(ActivityInfo activityInfo) {
        // 读配置库
        loadConfigFromDb(activityInfo);
        // 加场景
        CrossSceneMgr.initActivity(activityInfo);
    }

    public void loadConfigFromDb(ActivityInfo activityInfo) {
        initMaxRankConfig(activityInfo.getActivityId());
        initUnionZhanGongLevelConfig(activityInfo.getActivityId());

        config = CrossChuHanConfigMgr.getConfig(activityInfo.getActivityId());
    }

    public ChuHanConfig getConfig() {
        return config;
    }

    private void initMaxRankConfig(int activityId) {
        userMaxRank = getMaxRankConfig(ActivityInfoMgr.getConditionInfoList(activityId, eGamePlayerEventType.ChuHanUserZhanGongRank.getValue()));
        unionMaxRank = getMaxRankConfig(ActivityInfoMgr.getConditionInfoList(activityId, eGamePlayerEventType.ChuHanCampUnionZhanGongRank.getValue()));
        campMaxRank = getMaxRankConfig(ActivityInfoMgr.getConditionInfoList(activityId, eGamePlayerEventType.ChuHanCampScoreRank.getValue()));
    }

    private void initUnionZhanGongLevelConfig(int activityId) {
        List<ActivityConditionInfo> conditionInfoList = ActivityInfoMgr.getConditionInfoList(activityId, eGamePlayerEventType.ChuHanUnionZhanGong.getValue());
        List<Long> tempList = new ArrayList<>();
        for (ActivityConditionInfo conditionInfo : conditionInfoList) {
            tempList.add(conditionInfo.getParamList().get(3).longValue());
        }
        unionZhanGongLevelParams = tempList;
    }

    private int getMaxRankConfig(List<ActivityConditionInfo> list) {
        int maxRank = 0;
        for (ActivityConditionInfo conditionInfo : list) {
            int tmp = conditionInfo.getParamList().get(1).intValue();
            if (tmp > 0 && maxRank < tmp) {
                maxRank = tmp;
            }
        }
        return maxRank;
    }

    // ============================== 发消息 ==============================

    protected void sendPacket(int code, AbstractMessage.Builder<?> messageBuilder, long userId) {
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
        if (userBaseInfo == null) {
            return;
        }
        YanQuMessage message = YanQuMessageUtils.buildMessage(code, messageBuilder);
        MessageHelper.sendPacket(userBaseInfo.getServerId(), userId, message);
    }

    protected void sendPacketToAll(int code, AbstractMessage.Builder<?> messageBuilde, Collection<Long> userIdList) {
        TongBingProto.TongBingAgentTransferMsg.Builder agentMsg = TongBingProto.TongBingAgentTransferMsg.newBuilder();
        agentMsg.setCode(code);
        agentMsg.addAllUserId(userIdList);
        agentMsg.setMsg(messageBuilde.build().toByteString());

        YanQuMessage message = YanQuMessageUtils.buildMessage(AgentProtocol.A_TONG_BING_TRANSFER, agentMsg);
        for (Long serverId : config.getActivityInfo().getServerIdList()) {
            MessageHelper.sendPacket(serverId, 0, message);
        }
    }

    public int getUnionZhanGongLevel(long unionZhanGong) {
        int result = 0;
        for (int i = 0; i < unionZhanGongLevelParams.size(); i++) {
            int level = i + 1;
            if (unionZhanGong >= unionZhanGongLevelParams.get(i)) {
                result = level;
            } else {
                break;
            }
        }
        return result;
    }

    protected Object getUserLock(long userId) {
        Object userLock = userLockMap.get(userId);
        if (userLock == null) {
            synchronized (userLockMap) {
                userLock = userLockMap.get(userId);
                if (userLock == null) {
                    userLock = new Object();
                    userLockMap.put(userId, userLock);
                }
            }
        }
        return userLock;
    }
}
